<template>
  <div class="main">
    <a-spin :spinning="loading" tip="正在登录中，请稍等。。。">
      <a-form :form="form" class="user-layout-login" ref="formLogin" id="formLogin">
        <a-tabs
          :activeKey="customActiveKey"
          :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
          @change="handleTabClick">
          <a-tab-pane key="tab1" tab="绑定手机号">
            <div class="ant-modal-confirm-body-wrapper">
              <a-form-item>
                <a-input
                  size="large"
                  type="text"
                  placeholder="手机号"
                  v-model="thirdPhone">
                  <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-item>
              <a-form-item>
                <j-select-depart v-model="thirdDept"/>
              </a-form-item>
              <a-row :gutter="16">
                <a-col class="gutter-row" :span="16">
                  <a-form-item>
                    <a-input
                      size="large"
                      type="text"
                      placeholder="请输入验证码"
                      v-model="thirdCaptcha">
                      <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col class="gutter-row" :span="8">
                  <a-button
                    class="getCaptcha"
                    tabindex="-1"
                    :disabled="thirdState.smsSendBtn"
                    @click.stop.prevent="getThirdCaptcha"
                    v-text="!thirdState.smsSendBtn && '获取验证码' || (thirdState.time+' s')"></a-button>
                </a-col>
              </a-row>
            </div>
          </a-tab-pane>
        </a-tabs>
        <a-form-item style="margin-top:24px">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            :loading="loginBtn"
            @click.stop.prevent="thirdHandleOk"
            :disabled="loginBtn">确定
          </a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { postAction, getAction } from '@/api/manage'
import { timeFix, welcome } from '@/utils/util'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO, USER_NAME } from '@/store/mutation-types'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'

export default {
  components: {
    JSelectDepart
  },
  data() {
    return {
      loading: true,
      customActiveKey: 'tab1',
      form: this.$form.createForm(this),
      loginBtn: false,
      thirdPhone: '',
      thirdCaptcha: '',
      // 获取验证码按钮30s之内是否可点击
      thirdState: {
        time: 30,
        smsSendBtn: false
      },
      source: 'wechat_enterprise_web',
      // 第三方用户UUID
      thirdLoginInfo: '',
      thirdUserUuid: '',
      thirdType: '',
      thirdDept: '',
      thirdLoginState: false,
      url: {
        bindingThirdPhone: '/sys/thirdLogin/bindingThirdPhone'
      },
      validatorRules: {
        mobile: { rules: [{ validator: this.validateMobile }] },
        captcha: { rule: [{ required: true, message: '请输入验证码!' }] },
        inputCode: { rules: [{ required: true, message: '请输入验证码!' }] }
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    }
  },
  created() {
    this.currdatetime = new Date().getTime()
    Vue.ls.remove(ACCESS_TOKEN)
    this.getRouterData()
    this.loginThirdPhone()
  },
  methods: {
    ...mapActions(['Login', 'Logout', 'PhoneLogin', 'ThirdLogin']),
    getRouterData() {
      this.$nextTick(() => {
        if (this.$route.params.username) {
          this.form.setFieldsValue({
            'username': this.$route.params.username
          })
        }
      })
    },
    handleTabClick(key) {
      this.customActiveKey = key
    },
    // 绑定手机号点击确定按钮
    thirdHandleOk() {
      let bingingParams = {}
      bingingParams.mobile = this.thirdPhone
      bingingParams.captcha = this.thirdCaptcha
      bingingParams.thirdUserUuid = this.thirdUserUuid
      bingingParams.thirdDept = this.thirdDept
      postAction(this.url.bindingThirdPhone, bingingParams).then(res => {
        if (res.success) {
          this.doThirdLogin(res.result)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 获取第三方验证码
    getThirdCaptcha() {
      let that = this
      if (!this.thirdPhone) {
        that.cmsFailed('请输入手机号')
      } else {
        this.thirdState.smsSendBtn = true
        let interval = window.setInterval(() => {
          if (that.thirdState.time-- <= 0) {
            that.thirdState.time = 30
            that.thirdState.smsSendBtn = false
            window.clearInterval(interval)
          }
        }, 1000)
        const hide = this.$message.loading('验证码发送中..', 0)
        let smsParams = {}
        smsParams.mobile = this.thirdPhone
        smsParams.smsmode = '1'
        postAction('/sys/sms', smsParams).then(res => {
          if (!res.success) {
            setTimeout(hide, 0)
            this.cmsFailed(res.message)
          }
          setTimeout(hide, 500)
        }).catch(err => {
          setTimeout(hide, 1)
          clearInterval(interval)
          that.thirdState.time = 30
          that.thirdState.smsSendBtn = false
          this.requestFailed(err)
        })
      }
    },
    loginThirdPhone() {
      let that = this

      let code = that.GetQuery('code')
      let state = that.GetQuery('state')
      that.thirdType = that.source
      that.thirdLoginInfo = ''
      that.thirdLoginState = false
      if (that.IsNullOrEmpty(code)) {
        getAction('/sys/thirdLogin/render/phone/' + that.thirdType).then(res => {
          if (res.success) {
            window.location.replace(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      } else {
        getAction('/sys/thirdLogin/phone/' + that.thirdType + '/callback', { code: code, state: state }).then(res => {
          if (res.success) {
            let token = res.result.token
            if (typeof token === 'string') {
              // 如果是字符串类型 说明是token信息
              if (token === '登录失败') {
                that.$message.warning(token)
              } else if (token.includes('绑定手机号')) {
                that.loading = false
                let strings = token.split(',')
                that.thirdUserUuid = strings[1]
              } else {
                that.doThirdLogin(token)
              }
            } else {
              that.$message.warning('不识别的信息传递')
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    },
    // 根据token执行登录
    doThirdLogin(token) {
      if (this.thirdLoginState === false) {
        this.thirdLoginState = true
        let param = {}
        param.thirdType = this.thirdType
        param.token = token
        this.ThirdLogin(param).then(res => {
          if (res.success) {
            this.loginSuccess()
          } else {
            this.requestFailed(res)
          }
        })
      }
    },
    loginSuccess() {
      // update-begin- author:sunjianlei --- date:20190812 --- for: 登录成功后不解除禁用按钮，防止多次点击
      // this.loginBtn = false
      // update-end- author:sunjianlei --- date:20190812 --- for: 登录成功后不解除禁用按钮，防止多次点击
      this.$router.push({ path: '/dashboard/analysis' }).catch(() => {
        console.log('登录跳转首页出错,这个错误从哪里来的')
      })
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`
      })
    },
    requestFailed(err) {
      this.$notification['error']({
        message: '登录失败',
        description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.loginBtn = false
    },
    cmsFailed(err) {
      this.$notification['error']({
        message: '登录失败',
        description: err,
        duration: 4
      })
    },
    GetQuery: function (key) {
      let search = location.search.slice(1) // 得到get方式提交的查询字符串
      let arr = search.split('&')
      for (let i = 0; i < arr.length; i++) {
        let index = arr[i].indexOf('=')
        let ar = arr[i].substring(0, index)
        if (ar == key) {
          return arr[i].substring(index + 1)
        }
      }
      return ''
    },
    IsNullOrEmpty: function (str) {
      let res = false
      if (str == '' || str == undefined) {
        res = true
      }
      return res
    }
  }
}
</script>

<style lang="less" scoped>

.erweima {
  text-align: center;
  height: 320px
}

#wx_reg {
  transform: scale(0.8);
  transform-origin: top center;
  margin-top: 15px;
}

.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, .2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color .3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}

</style>
<style>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
</style>
